from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from  rest_framework.viewsets import ReadOnlyModelViewSet

from meiduo_admin.serializers.orders import OrderInfoSerializer
from meiduo_admin.serializers.user import PageNum
from orders.models import OrderInfo


class OrdersView(ReadOnlyModelViewSet):
    queryset = OrderInfo.objects.all()
    pagination_class = PageNum
    serializer_class = OrderInfoSerializer
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword == '' or keyword is None:
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id__contains=keyword)
    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        status = request.data.get('status')
        if status is None:
            return Response({'error':"未提交状态信息"})
        try:
            order = OrderInfo.objects.get(id=pk)
        except Exception as e:
            return Response({'error':"订单信息有误"})
        else:
            order.status = status
            order.save()
            return Response({
                'order_id':order.id,
                'status':status
            })
